class Notifier < ActionMailer::Base

  def receive(email)
    
    #b = email.body.chomp.strip.squeeze(" ")
    #phone_number = d[0]
    #command = d[1]
    b = email.body.split("\n")
    m = b[0]
    t = b[1]
    
    phone_number = m.split(":")[1].gsub(Regexp.new(/^34/),'')
    command = t.split(":")[1].chomp.strip.squeeze(" ")
    
    if u = User.find_by_phone(phone_number)
      Message.create(:subject => email.subject, :body => command)
      Command.create(:body => command, :phone_number => phone_number, :user_id => u.id)
    end
  end

  # Confirms the presence has been registered OK
  def report_reception_ok(presence)
    @subject    = 'Notifier#reception_ok'
    @body       = {:identifier => presence.identifier, :login => presence.user.login }
    @recipients =  [presence.user.email]
    @from       = 'MmM'
    @sent_on    = Time.now
    @headers    = {}
  end
  
  
  def report_buddies_to_user(presence, buddies)
    @subject    = 'Notifier#who_is_here'
    @body       = {:buddies => buddies, :presence => presence}
    @recipients =  [presence.user.email, presence.user.phone]
    @from       = 'MmM'
    @sent_on    = Time.now
    @headers    = {}
  end
  
  def report_to_buddies_user_is_here(presence, buddy)

    @subject    = 'Notifier#user_is_here'
    @body       = {:user => presence.user.identities.first.login, :service => presence.user.identities.first.service}
    @recipients =  [buddy.email, buddy.phone]
    @from       = 'MmM'
    @sent_on    = Time.now
    @headers    = {}
  end
  
  def report_got_ping(recipient, sender, body, aka)
    @subject    = 'Notifier#got_ping'
    @body       = {:sender => sender, :body => body, :aka => aka}
    @recipients =  [recipient.email, recipient.phone]
    @from       = 'MmM'
    @sent_on    = Time.now
    @headers    = {}
  end
  
  # errores
  def report_tried_to_ping_invalid_recipient(user, aka)
    @subject    = 'Notifier#tried_to_ping_invalid_recipient'
    @body       = {:aka => aka}
    @recipients =  [user.email]
    @from       = 'MmM'
    @sent_on    = Time.now
    @headers    = {}
  end
  
end
